import { Button, Row, Col, Modal } from "antd";
import {
  WeaTools,
  WeaSearchGroup,
  WeaRightMenu,
  WeaFormItem,
  WeaTop,
  WeaCheckbox,
  WeaSelect,
  WeaDatePicker,
  WeaDialog,
  WeaAlertPage,
  WeaLocaleProvider,
} from "ecCom";
import isEmpty from "lodash/isEmpty";
import forEach from "lodash/forEach";
import { WeaSwitch } from "comsMobx";
import { inject, observer } from "mobx-react";
import * as mobx from "mobx";
import moment from "moment";
import "../../style/systeminfo.less";
import InputBtn from "../../coms/inputBtn";
import TopButton from "../../coms/topButton";
import NeedAutoBtn from "../../coms/needAutoBtn";
import { i18n } from "../../public/i18n";
const getKey = WeaTools.getKey;
const toJS = mobx.toJS;
const confirm = Modal.confirm;
const getLabel = WeaLocaleProvider.getLabel;

@inject("hrmSystemInfo")
@inject("hrmCard")
@observer
class HrmSystemInfo extends React.Component {
  componentDidMount() {
    const { hrmSystemInfo, hrmCard } = this.props;
    hrmSystemInfo.init();
    hrmSystemInfo.hrmId = this.props.params.hrmId || "";
    hrmSystemInfo.getFormField();
    hrmSystemInfo.getWeekInfo(new moment().format("YYYY-MM-DD"));
    const dom = $(
      '<Object id="htactx" name="htactx" classid="clsid:FB4EE423-43A4-4AA9-BDE9-4335A6D3C74E" codebase="HTActX.cab#version=1,0,0,1" style="HEIGHT: 0px; WIDTH: 0px"></Object>'
    );
    $(document.body).append(dom);
    hrmCard.setTopButtons(this.getTopButtons);
    hrmCard.setTopRightMenus(this.getRightMenu);
    hrmCard.setTopShowDropIcon(true);
  }

  getSearchs = () => {
    const { hrmSystemInfo } = this.props;
    let {
      isEditor,
      checkValue,
      inputVlaue,
      pickerValue,
      selectValue,
      options,
      formFields,
      form,
    } = hrmSystemInfo;
    const formParams = hrmSystemInfo.getFormParams();
    const userUsbType = formParams.userUsbType || "";
    const usbState = formParams.usbstate || "";
    const { date } = hrmSystemInfo;
    const cancelSecondPwd = () => {
      confirm({
        title: i18n.confirm.defaultTitle(),
        content: (
          <div>
            <div>{i18n.label["388923"]()}</div>
            <div>{i18n.label["388924"]()}</div>
          </div>
        ),
        okText: i18n.button.ok(),
        cancelText: i18n.button.cancel(),
        width: 420,
        onOk: () => {
          form.updateFields({
            useSecondaryPwd: {
              value: "0",
            },
          });
        },
      });
    };

    const { isFormInit } = form;
    let group = [];
    let group1 = [];
    let colIndex = 1;
    isFormInit &&
      formFields.forEach((c, i) => {
        c.items.forEach((field, j) => {
          let domkey = field.domkey[0] || "";
          let hide = false;
          let hideLabel = false;
          let is901 = userUsbType == "901";

          if (
            userUsbType == "" &&
            (domkey == "tokenKey" || domkey == "serial" || domkey == "usbstate")
          )
            hide = true;
          if (
            userUsbType == "4" &&
            (domkey == "tokenKey" || domkey == "serial")
          )
            hide = true;
          if (userUsbType == "2" && domkey == "tokenKey") hide = true;
          if (userUsbType == "3" && domkey == "serial") hide = true;
          if (is901 && ["tokenKey", "serial"].indexOf(domkey) >= 0) {
            hide = true;
          }
          if (!isEditor && (domkey == "password" || domkey == "password1"))
            hide = true;
          if (domkey === "validatecode") {
            hide = isEditor ? false : true;
          }

          if (domkey == "startUsing") {
            hide = true;
            if (
              isEditor &&
              (userUsbType == "3" || userUsbType == "4") &&
              usbState == "1"
            ) {
              hide = false;
            }
          }

          if (!hide) {
            let dom;
            if (isEditor && domkey == "tokenKey") {
              hideLabel = true;
              const key = getKey(field);
              const bindObj = form.$(key);
              dom = (
                <div>
                  <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@msn9sk@${j}`}>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@cmw0e7@${j}`} span={7}>
                      <span>{i18n.label.tokenNum()}: </span>
                    </Col>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@46ev1j@${j}`} span={17}>
                      <InputBtn ecId={`${this && this.props && this.props.ecId || ''}_InputBtn@rimd4i`}
                        btnText={i18n.label.binding()}
                        {...bindObj.bind()}
                        viewAttr={3}
                        onBtnClick={(v) => this.updateKey()}
                      />
                    </Col>
                  </Row>
                </div>
              );
            } else if (isEditor && domkey == "serial") {
              hideLabel = true;
              const key = getKey(field);
              const bindObj = form.$(key);
              dom = (
                <div>
                  <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@khq2m4@${j}`}>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@x3qzk4`} span={7}>
                      <span>{i18n.label.userKey()}: </span>
                    </Col>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@zm5n2j`} span={17}>
                      <InputBtn ecId={`${this && this.props && this.props.ecId || ''}_InputBtn@z4yita`}
                        btnText={i18n.label.binding()}
                        {...bindObj.bind()}
                        viewAttr={3}
                        onBtnClick={(v) => this.updateKey(v)}
                      />
                    </Col>
                  </Row>
                </div>
              );
            } else if (isEditor && domkey == "startUsing") {
              hideLabel = true;
              dom = (
                <div>
                  <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@uicyvk`} style={{ lineHeight: "40px" }}>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@a5uyo4`} span={6}>
                      <span>{i18n.label.autoEnable()}：</span>
                    </Col>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@67onpo`} span={18}>
                      <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@1mjy6m`}
                        display="switch"
                        value={checkValue}
                        onChange={this.onCheckChange}
                      />
                    </Col>
                  </Row>
                  {checkValue && checkValue == "1" && (
                    <div>
                      <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@7yx7ts`} style={{ lineHeight: "40px" }}>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@aas59z`} span={6}>
                          <span>{i18n.label.enableDate()}：</span>
                        </Col>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@2on656`} span={18}>
                          <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@wurx8j`}
                            noInput
                            startValue={new Date()}
                            viewAttr={3}
                            value={pickerValue}
                            onChange={this.onPickerChange}
                          />
                        </Col>
                      </Row>
                      <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@8byq0n`} style={{ lineHeight: "40px" }}>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@sbq3zd`} span={6}>
                          <span>{i18n.label.enableMode()}：</span>
                        </Col>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4p0402`} span={18}>
                          <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@qefxjy`}
                            options={options}
                            viewAttr={3}
                            value={selectValue}
                            onChange={this.onSelectChange}
                          />
                        </Col>
                      </Row>
                    </div>
                  )}
                </div>
              );
            } else if (domkey == "useSecondaryPwd") {
              dom = (
                <div className="wea-field-readonly">
                  {formParams.useSecondaryPwd === "1"
                    ? i18n.label["15809"]()
                    : i18n.label["15808"]()}
                </div>
              );
            } else {
              dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@jwauuu`} fieldConfig={field} form={form} />;
            }

            if (!isEditor) {
              if (colIndex % 2 == 0) {
                group1.push(
                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ysix7b@${j}`}
                    underline
                    label={`${field.label}`}
                    labelCol={{ span: `${window.HrmLabelCol}` }}
                    wrapperCol={{ span: `${window.HrmWrapperCol}` }}
                  >
                    {dom}
                  </WeaFormItem>
                );
              } else {
                group.push(
                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@4wy145@${j}`}
                    underline
                    hideLabel={hideLabel}
                    label={`${field.label}`}
                    labelCol={{ span: `${window.HrmLabelCol}` }}
                    wrapperCol={{ span: `${window.HrmWrapperCol}` }}
                  >
                    {dom}
                  </WeaFormItem>
                );
              }
              colIndex++;
            } else {
              if (
                domkey == "password" ||
                domkey == "password1" ||
                domkey == "seclevel"
              ) {
                group1.push(
                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@yaigya@${j}`}
                    label={`${field.label}`}
                    labelCol={{ span: `${field.labelcol}` }}
                    wrapperCol={{ span: `${field.fieldcol}` }}
                  >
                    {dom}
                  </WeaFormItem>
                );
              } else if (domkey == "useSecondaryPwd") {
                group1.push(
                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@bim9k6@${j}`}
                    label={`${field.label}`}
                    labelCol={{ span: `${field.labelcol}` }}
                    wrapperCol={{ span: `${field.fieldcol}` }}
                  >
                    <div>
                      <div
                        style={{
                          float: "left",
                          lineHeight: "30px",
                          marginRight: "30px",
                        }}
                      >
                        {formParams.useSecondaryPwd === "1"
                          ? i18n.label["15809"]()
                          : i18n.label["15808"]()}
                      </div>
                      {formParams.useSecondaryPwd === "1" && (
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4skmcr@${j}`}
                          style={{ float: "left" }}
                          type="primary"
                          onClick={() => cancelSecondPwd()}
                        >
                          {i18n.label["26471"]()}
                        </Button>
                      )}
                    </div>
                  </WeaFormItem>
                );
              } else if (domkey === "validatecode") {
                group1.push(
                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@yec9mg@${j}`}
                    label={`${field.label}`}
                    labelCol={{ span: `${field.labelcol}` }}
                    wrapperCol={{ span: `${field.fieldcol}` }}
                  >
                    {dom}
                    <img
                      src={`/weaver/weaver.file.MakeValidateCode?isView=1&validatetype=0&validatenum=4&seriesnum_=${date}`}
                      style={{
                        cursor: "pointer",
                        position: "absolute",
                        top: -5,
                        left: "105%",
                      }}
                      onClick={() => (hrmSystemInfo.date = new Date().getTime())}
                    />
                  </WeaFormItem>
                );
              } else if (is901 && domkey == "usbstate") {
                let statesOptions = Array.from(field.options);
                statesOptions.pop();

                group.push(
                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@uzbtbc@${j}`}
                    hideLabel={hideLabel}
                    label={field.label}
                    labelCol={{ span: field.labelcol }}
                    wrapperCol={{ span: field.fieldcol }}
                  >
                    <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@2tv9ju@${j}`}
                      options={statesOptions}
                      value={field.value}
                      onChange={(v, showname) => {
                        this.changeUsbstate(v);
                      }}
                    />
                  </WeaFormItem>
                );
              } else {
                group.push(
                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@jrrl9g@${j}`}
                    hideLabel={hideLabel}
                    label={`${field.label}`}
                    labelCol={{ span: `${field.labelcol}` }}
                    wrapperCol={{ span: `${field.fieldcol}` }}
                  >
                    {dom}
                  </WeaFormItem>
                );
              }
            }
          }
        });
      });

    return (
      <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@qz8lpu`}>
        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@tnalgy`} span={12}>{group}</Col>
        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@35m9rx`} span={12}>{group1}</Col>
      </Row>
    );
  }

  render() {
    const { hrmSystemInfo } = this.props;
    const { viewDate, isEditor, weekInfo, title, doSave } = hrmSystemInfo;
    const formParams = hrmSystemInfo.getFormParams();
    const { query } = this.props.location;
    if (
      !query.fromcard &&
      window.location.href.indexOf("/spa/hrm/index_mobx.html") > -1
    ) {
      document.title = i18n.label.sysInfo();
    }

    try{
      let coms;
      if(!query.fromcard){
        coms = (
          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@oipzs7`} datas={this.getRightMenu()}>
            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@71juxj`}
              title={title()}
              icon={<i className="icon-coms-hrm" />}
              iconBgcolor="#217346"
              buttons={this.getTopButtons()}
              buttonSpace={10}
              showDropIcon={true}
              dropMenuDatas={this.getRightMenu()}
            >
              <div className="hrm-my-card-basicInfo hrm-my-cardInfo wea-myhrm-systeminfo">
                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@67gu6q`}
                needTigger={true}
                title={i18n.label.sysInfo()}
                showGroup={true}
                >
                {this.getSearchs()}
                </WeaSearchGroup>
              </div>
            </WeaTop>
          </WeaRightMenu>
        )
      }else{
        coms = (
          <div className="hrm-my-card-basicInfo hrm-my-cardInfo wea-myhrm-systeminfo">
            <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@76xqqb`}
            needTigger={true}
            title={i18n.label.sysInfo()}
            showGroup={true}
            >
            {this.getSearchs()}
            </WeaSearchGroup>
          </div>
        )
      }


      return (
        <React.Fragment ecId={`${this && this.props && this.props.ecId || ''}_undefined@we1g11`}>
          <div
            className="wea-myhrm-systeminfo wea-myhrm"
            style={{ background: "#ffffff", minHeight: window.innerHeight - 146 }}
          >
        {coms}
          </div>
        </React.Fragment>
      );
    }catch(e){
      return (
        <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@hex0bh`}>
          <div style={{ color: '#000' }}>{i18n.message.authFailed()}</div>
      </WeaAlertPage>
      )
    }
  }

  getTopButtons = () => {
    const { hrmSystemInfo } = this.props;
    const { isEditor, buttons } = hrmSystemInfo;

    const save = (
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xrophl`} type="primary" onClick={this.doSave}>
        {i18n.button.save()}
      </Button>
    );
    const back = (
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qe01oj`} type="primary" onClick={this.backCard}>
        {i18n.button.back()}
      </Button>
    );
    const edit = (
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@g3eerr`} type="primary" onClick={this.edit}>
        {i18n.button.modify()}
      </Button>
    );
    const btns = [];
    try{
      if (isEditor) {
        if (buttons && buttons.hasEdit) {
          btns.push(save);
          btns.push(back);
        }
      } else {
        if (buttons && buttons.hasEdit) {
          btns.push(edit);
        }
      }
    }catch(e){}
    return btns;
  }

  doSave = () => {
    const { hrmSystemInfo } = this.props;
    hrmSystemInfo.doSave();
  }

  edit = () => {
    const { hrmSystemInfo } = this.props;
    hrmSystemInfo.edit();
  }

  backCard = () => {
    const { hrmSystemInfo } = this.props;
    hrmSystemInfo.backCard();
  }

  updateKey = () => {
    const { hrmSystemInfo } = this.props;
    hrmSystemInfo.updateKey();
  }

  onPickerChange = (v) => {
    const { hrmSystemInfo } = this.props;
    hrmSystemInfo.onPickerChange(v);
  }

  onCheckChange = (v) => {
    const { hrmSystemInfo } = this.props;
    hrmSystemInfo.onCheckChange(v);
  }

  onSelectChange = (v) => {
    const { hrmSystemInfo } = this.props;
    hrmSystemInfo.onSelectChange(v);
  }

  getRightMenu = () => {
    const { hrmSystemInfo } = this.props;
    const { isEditor, buttons, hrmId } = hrmSystemInfo;

    let arr = [];
    try{
      if (buttons && buttons.hasEdit) {
        if (isEditor) {
          arr = [
            {
              icon: <i className="icon-coms-common" />,
              content: i18n.button.save(),
              key: "save",
              onClick: (key) => {
                this.doSave();
              },
            },
            {
              icon: <i className="icon-coms-go-back" />,
              content: i18n.button.back(),
              key: "back",
              onClick: (key) => {
                this.backCard();
              },
            },
          ];
        } else {
          arr = [
            {
              icon: <i className="icon-coms-edit" />,
              content: i18n.button.modify(),
              key: "edit",
              onClick: (key) => {
                this.edit();
              },
            },
          ];
          arr.push({
            icon: <i className="icon-coms-Print-log" />,
            content: i18n.button.log(),
            key: "showLog",
            onClick: (key) => {
              window.setLogViewProps({
                logSmallType: i18n.smallType.HRM_RSOURCE_CARD_SYSTEM,
                targetId: hrmId,
              });
            },
          });
        }
      }
    }catch(e){}
    return arr;
  }

  changeUsbstate = (v) => {
    const {
      hrmSystemInfo: { form },
    } = this.props;
    form.updateFields({
      usbstate: {
        value: v,
      },
    });
  };
}

export default HrmSystemInfo;
